<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.userName" placeholder="请输入用户名" style="width: 200px" class="filter-item" />
      <el-input v-model="listQuery.personName" placeholder="请输入人员名" style="width: 200px" class="filter-item" />
      <!-- <el-select v-model="listQuery.department" placeholder="请选择所属单位" clearable style="width: 200px;"
        class="filter-item">
        <el-option v-for="item in departmentOptions" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select> -->
      <el-select v-model="listQuery.job" placeholder="请选择职务" clearable style="width: 200px;" class="filter-item">
        <el-option v-for="item in jobOptions" :value="item"> </el-option>
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" type="success" @click="createUser">
        创建账号
      </el-button>
    </div>
    <div class="block block-custom">
      <el-table v-loading="loading" :data="tableData" style="width: 100%" height="calc(85vh - 155px)">
        <el-table-column label="序号" prop="id" sortable="custom" align="center" width="80">
          <template slot-scope="scope">
            <span>{{ (listQuery.page - 1) * listQuery.size + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="userName" align="center" label="用户名" />
        <el-table-column prop="personName" align="center" label="人员名" />
        <el-table-column prop="gender" align="center" label="性别" />
        <el-table-column prop="department" align="center" label="所属单位" min-width="100"/>
        <el-table-column prop="job" align="center" label="职务" />
        <el-table-column prop="phoneNum" align="center" label="电话"/>
        <el-table-column label="操作" align="center" min-width="180">
          <template slot-scope="scope">
            <el-button size="medium" type="primary" @click="HandleChangeRole(scope.row)">设置角色</el-button>
            <el-button size="medium" type="warning" @click="updateUserInfo(scope.row)">修改信息</el-button>
            <el-button size="medium" type="danger" @click="delUser(scope.row.userId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.size" @pagination="getList" />

    <el-dialog title="设置角色" :visible.sync="roleDialogFormVisible">
      <template>
        <div>
          <span class="use-name">用户名：</span>
          <span>{{ nowUserName }}</span>
        </div>
        <div style="margin: 20px 0;" />
        <div>
          <span class="use-name">角色选择：</span>
        </div>
        <div style="margin: 20px 0;" />
        <el-checkbox-group v-model="checkedRole" @change="handlecheckedRoleChange">
          <el-checkbox v-for="role in roles" :key="role.roleId" :label="role.roleName">{{ role.roleName }}</el-checkbox>
        </el-checkbox-group>
      </template>
      <div slot="footer" class="dialog-footer">
        <el-button @click="roleDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="HandleRoleSubmit()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="formTextMap[formOperationType]" :visible.sync="userDialogFormVisible" :modal="true"
      custom-class="ly-running-info-body" @close="createUserDialogClosed" class="view-dialog" :show-close="false">
      <el-form ref="userForm" :model="userForm" label-width="40%" style="width:60%;" :rules="rules">
        <el-form-item label="用户名:" prop="userName">
          <el-input v-model="userForm.userName" />
        </el-form-item>
        <el-form-item v-if="formOperationType == 'create'" label="密码：" prop="password">
          <el-input v-model="userForm.password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item v-if="formOperationType == 'create'" label="确认密码：" prop="password1">
          <el-input v-model="userForm.password1" placeholder="请再次输入密码" show-password />
        </el-form-item>
        <el-form-item label="人员名:">
          <el-input v-model="userForm.personName" />
        </el-form-item>
        <el-form-item label="用户介绍:">
          <el-input type="textarea" :rows="2" placeholder="请输入用户介绍" v-model="userForm.introduction" />
        </el-form-item>
        <el-form-item label="性别:">
          <el-select v-model="userForm.gender" placeholder="请选择性别">
            <el-option v-for="item in genderOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="生日:">
          <el-date-picker v-model="userForm.birthday" type="date" placeholder="选择日期" format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd" style="width: 100%;" placement="bottom-start" :picker-options="pickerOptions0">
          </el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="所属单位:">
                  <el-select v-model="userForm.department" placeholder="请选择所属单位" style="width: 40%;">
                    <el-option v-for="item in departmentOptions" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item> -->
        <el-form-item label="职务:">
          <el-select v-model="userForm.job" placeholder="请选择职务" style="width: 60%;">
            <el-option v-for="item in jobOptions" :value="item">
            </el-option>
          </el-select>
          <el-button type="success" icon="el-icon-edit" @click="showJobs" style="width: 35%;">编辑职务信息</el-button>
          <el-dialog width="30%" title="编辑职务信息" :visible.sync="innerVisible" append-to-body class="view-dialog"
            :close-on-click-modal="false" :show-close="false">
            <el-form>
              <el-form-item>
                <el-tag :key="tag" v-for="tag in dynamicTags" closable :disable-transitions="false"
                  @close="handleClose(tag)">
                  {{ tag }}
                </el-tag>
                <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="small"
                  @blur="handleInputConfirm">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 新建职务</el-button>
              </el-form-item>
              <el-form-item label-width="55%">
                <el-button size="small" round type="primary" @click="handleAddOrUpdateJobs">确定修改</el-button>
                <el-button size="small" round @click="cancelAddOrUpdateJobs">取消</el-button>
              </el-form-item>
            </el-form>
          </el-dialog>
        </el-form-item>
        <el-form-item label="手机号:">
          <el-input v-model="userForm.phoneNum" required />
        </el-form-item>
        <el-form-item label="邮箱:">
          <el-input v-model="userForm.email" />
        </el-form-item>
        <el-form-item label="所属部门:">
          <el-cascader v-model="userForm.org" :options="orgOptions" :props="orgProps" style="width: 100%;"
            @change="orgChanged" ref="tree">
          </el-cascader>
        </el-form-item>
        <el-form-item label="所属车站:">
          <el-select v-model="userForm.stationIds" multiple placeholder="请选择" style="width: 100%;"
            @change="stationChanged">
            <el-option v-for="station in stationNames" :key="station.stationNum" :label="station.stationName"
              :value="station.stationNum">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label-width="55%">
          <el-button v-if="formOperationType == 'edit'" type="danger" @click="resetPassword">重置密码</el-button>
          <el-button v-if="formOperationType == 'create'" type="primary" @click="addUserSubmit">立即创建</el-button>
          <el-button v-else type="primary" @click.native="updateUserSubmit">确定修改</el-button>
          <el-button @click="createUserDialogClosed">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { getOptions, addOrUpdateOptions, getUserPageInfos, checkRegistered, deleteUser, createOrUpdate, resetPwd, updateUserRoles } from '@/api/user'
import { getRoles } from '@/api/role'
import Pagination from '@/components/Pagination'
import { setOrgOptions } from '../../memberOrgs'
import { updateMemberOrgs } from '@/api/organization'
import { getStationNames, addOrUpdateMemberStations } from "@/api/station";
import { cloneDeep } from 'lodash'

export default {
  components: { Pagination },
  data() {
    var checkUserName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('用户名不能为空'));
      }
      setTimeout(() => {
        if (this.userForm.userName == this.userNameBeforeChange) {
          callback();
        }
        else {
          checkRegistered(value).then(res => {
            if (res.code !== 0) {
              callback(new Error(res.msg));
            } else {
              callback();
            }
          })
        }
      }, 1000);
    };
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.userForm.password1 !== '') {
          this.$refs.userForm.validateField('password1');
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.userForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 8.64e6;//如果没有后面的-8.64e6就是不可以选择今天的
        }
      },
      rules: {
        userName: [
          { required: true, validator: checkUserName, trigger: 'blur' }
        ],
        password: [
          { required: true, validator: validatePass, trigger: 'blur' }
        ],
        password1: [
          { required: true, validator: validatePass2, trigger: 'blur' }
        ]
      },
      stationNames: [
        {
          "stationName": "申西站",
          "stationNum": 1
        },
        {
          "stationName": "中心站",
          "stationNum": 2
        },
        {
          "stationName": "六矿",
          "stationNum": 3
        }
      ],
      isStationChanged: false,
      userNameBeforeChange: '',
      dynamicTags: [],
      inputVisible: false,
      inputValue: '',
      innerVisible: false,
      isOrgChanged: false,
      orgProps:
      {
        value: 'orgId',                 //匹配响应数据中的id
        label: 'orgName',               //匹配响应数据中的name
        children: 'children',        //匹配响应数据中的children
        checkStrictly: true
      },
      orgOptions: [],
      memberOrgForm: {
        memberId: 0,
        orgId: 0,
        memberType: 1
      },
      formOperationType: '',
      formTextMap: { create: '添加用户', edit: '修改用户' },
      nowUserName: {},
      checkedRole: [],
      roles: [],
      loading: true,
      tableData: [],
      total: 10,
      selectedRow: {},
      roleDialogFormVisible: false,
      listQuery: {
        userName: '',
        phoneNumber: '',
        personName: '',
        job: '',
        page: 1,
        size: 10
      },
      userDialogFormVisible: false,
      userForm: {
        department: '',
        userId: '',
        roles: '',
        userName: '',
        introduction: '',
        gender: '',
        birthday: '',
        org: [],
        job: '',
        phoneNum: '',
        password: '',
        password1: '',
        email: '',
        personName: '',
        stationIds: []
      },
      genderOptions: [
        {
          value: '男',
          label: '男'
        },
        {
          value: '女',
          label: '女'
        }
      ],
      jobOptions: []
    }
  },
  created: function () {
    this.getList()
    this.getRoleList()
    this.getOption()
    setOrgOptions().then(res => {
      this.orgOptions.push(res)
    })
    this.getStationNameList()
  },
  methods: {
    stationChanged() {
      this.isStationChanged = true
    },
    getStationNameList() {
      getStationNames().then(res => {
        this.stationNames = res.data
      })
    },
    cancelAddOrUpdateJobs() {
      this.dynamicTags = this.jobOptions
      this.innerVisible = false
    },
    handleAddOrUpdateJobs() {
      var jobData = { "optionName": '', "optionJson": '' }
      jobData.optionName = "jobs"
      jobData.optionJson = this.dynamicTags
      addOrUpdateOptions(jobData).then(res => {
        if (res.code == 0) {
          this.jobOptions = this.dynamicTags
          this.$message.success('职务信息更新成功！')
          this.innerVisible = false
        } else {
          this.dynamicTags = this.jobOptions //白改，没作用
          this.$message.error(res.msg)
        }
      })
    },
    showJobs() {
      this.innerVisible = true
      this.dynamicTags = this.jobOptions
    },
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.dynamicTags.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = '';
    },
    getOption() {
      getOptions("jobs").then(res => {
        this.jobOptions = res.data
      })
    },
    orgChanged() {
      this.isOrgChanged = true
      // let data = this.$refs.tree.getCheckedNodes()[0].pathLabels.toString()
      // //用for循环遍历获取的数据,并把逗号裁掉
      // for (let i = 0; i < data.length; i++) {
      //   if (data[i] === ',') {
      //     data = data.replace(data[i], '/')
      //   }
      // }
      // this.userForm.department = data
    },
    getList: function () {
      this.loading = true
      // console.log(this.$store.getters.stationIds);
      this.listQuery.stationIds = this.$store.getters.stationIds.join(',');
      console.log(this.$store.getters.stationIds.join(', '));
      getUserPageInfos(this.listQuery).then(response => {
        this.tableData = response.data.items
        this.total = response.data.total
        this.loading = false
      })
    },
    calcPage() {
      let newPageing = Math.ceil((this.total - 1) / this.listQuery.size);//Math.ceil向上取整算出新的分页
      let currentPage = this.listQuery.page > newPageing ? newPageing : this.listQuery.page;//计算当前页应该是哪页
      this.listQuery.page = currentPage < 1 ? 1 : currentPage;//把当前页的值赋给this.page,重新渲染列表
    },
    getRoleList: function () {
      getRoles().then(res => {
        this.roles = res.data
      })
    },
    handleFilter: function () {
      this.getList()
    },
    //编辑更新用户信息
    updateUserInfo: function (row) {
      var that = this
      that.loading = true
      that.formOperationType = 'edit'
      that.userDialogFormVisible = true
      that.$nextTick(() => {
        // 弹框打开时初始化表单
        that.userForm = cloneDeep(row)
        this.userNameBeforeChange = that.userForm.userName
      })
      that.loading = false
    },
    delUser: function (id) {
      var that = this
      that.loading = true
      this.$confirm('此操作将永久删除该条目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteUser(id).then(res => {
          if (res.code === 0) {
            this.calcPage()// 20230224 删除时计算一下
            that.getList()
            that.$message.success('用户删除成功！')
          } else {
            that.$message.error(res.msg)
          }
          that.loading = false
        })
      }).catch(() => {
        that.loading = false
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    createUser: function () {
      var that = this
      that.loading = true
      that.formOperationType = 'create'
      that.userDialogFormVisible = true
      // var clonForm = {}
      that.$nextTick(() => {
        // 弹框打开时初始化表单
        Object.keys(this.userForm).forEach(key => {
          this.userForm[key] = null
        })
      })
      that.loading = false
    },
    addUserSubmit: function () {
      this.$refs['userForm'].validate(valid => {
        if (valid) {
          const formData = this.userForm
          this.SubmitFormData(formData)
        }
      })
    },
    updateUserSubmit: function () {
      this.$refs['userForm'].validate(valid => {
        if (valid) {
          const formData = this.userForm
          this.SubmitFormData(formData)
        }
      })
    },
    SubmitFormData(formData) {
      if (this.isStationChanged) {
        let data = {
          'stationIds': this.userForm.stationIds,
          'memberId': this.userForm.userId,
          'memberType': 1
        }
        addOrUpdateMemberStations(data).then(res=>{
          if (res.code != 0) {
            this.$message.error(res.msg)
          }
        })
      }
      createOrUpdate(formData).then(res => {
        if (res.data) {
          this.userForm.userId = res.data.userId
          if (this.isOrgChanged) {
            this.memberOrgForm.memberId = this.userForm.userId
            this.memberOrgForm.memberType = 1
            this.memberOrgForm.orgId = this.userForm.org.slice(-1)[0]
            updateMemberOrgs(this.memberOrgForm).then(res => {
              if (res.code == 0) {
                this.$message.success('用户信息提交成功')
              }
              else {
                this.$message.error(res.msg)
              }
              this.getList()
              Object.keys(this.userForm).forEach(key => {
                this.userForm[key] = null
              })
              this.userDialogFormVisible = false
              this.isOrgChanged = false
            })
          }
          else {
            this.$message.success('用户信息提交成功')
            this.getList()
            Object.keys(this.userForm).forEach(key => {
              this.userForm[key] = null
            })
            this.userDialogFormVisible = false
          }
        }
      }
      )
    },
    //dialogClosed 点击右上角x，关闭对话框则元素清空
    createUserDialogClosed() {
      Object.keys(this.userForm).forEach(key => (this.userForm[key] = ''));
      this.userNameBeforeChange = ''
      this.$refs["userForm"].resetFields();
      this.userDialogFormVisible = false
    },
    HandleChangeRole(row) {
      this.checkedRole = row.roles
      this.selectedRow = row
      this.roleDialogFormVisible = true
      this.nowUserName = row.userName
    },
    handlecheckedRoleChange(value) {
      // console.log(this.checkedRole, value)
    },
    HandleRoleSubmit() {
      const rolestr = this.checkedRole.join()
      var formData = { userId: '', roles: '' }
      formData.userId = this.selectedRow.userId
      // var formData = this.selectedRow
      formData.roles = rolestr.split(',')

      updateUserRoles(formData).then(res => {
        if (res.code === 0) {
          this.$message.success('角色修改成功')
          this.getList()
          this.roleDialogFormVisible = false
        }
      })
    },
    resetPassword() {
      var that = this
      const formData = that.userForm
      const userId = formData.userId
      const password = '123456'
      this.$confirm('此操作将重置密码, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          resetPwd(userId, password).then(res => {
            if (res.code === 0) {
              that.$message.success('密码重置成功')
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消重置密码'
          })
        })
    }
  }
}
</script>
<style scoped>
.block .el-range-separator {
  width: 24px;
}

/deep/ .el-table__body-wrapper::-webkit-scrollbar {
  width: 8px;
  /*滚动条宽度*/
  height: 8px;
  /*滚动条高度*/
}

/deep/ .el-table__body-wrapper::-webkit-scrollbar-track {
  border-radius: 0px;
  /*滚动条的背景区域的圆角*/
  background-color: rgba(2, 29, 87, 1);
  /*滚动条的背景颜色*/
}

/deep/ .el-table__body-wrapper::-webkit-scrollbar-corner {
  background-color: rgba(2, 29, 87, 1);
}

/deep/ .el-table__body-wrapper::-webkit-scrollbar-thumb {
  border-radius: 4px;
  /*滚动条的圆角*/
  background-color: rgba(24, 144, 255, 0.50);
  /*滚动条的背景颜色*/
}

/* .el-table__body-wrapper {
  height: calc(100% - 60px) !important;
} */

.use-name {
  font-size: 1rem;
  font-weight: 700;
  color: #606266;
}


/* 弹窗 */
/* 改变高度弹窗位置*/
/deep/ .dialog-content .el-dialog__body {
  height: 40vh;
  overflow: auto;
}

/deep/ .view-dialog>.el-dialog {
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #FFFFFF;
  border-radius: 12px;
  box-shadow: 2px 2px 5px #d0d0d0;
  max-height: calc(100%);
  max-width: calc(100%);
}

/deep/ .el-dialog .el-dialog__body {
  flex: 1;
  overflow: hidden auto;
  /* 隐藏水平滚动条，显示垂直滚动条 */
  /* overflow-y: scroll; 显示垂直滚动条 */
}

/deep/ .view-dialog>.el-dialog>.el-dialog__header {
  width: 100%;
  height: 54px;
  line-height: 54px;
  text-align: center;
  background: #F4F5F7;
  border-radius: 12px 12px 0px 0px;
  font-size: 20px;
  font-family: Source Han Sans CN;
  font-weight: 400;
  color: #252B3A;
  padding: 0 0 0 40px;
  padding-left: 0;
}

/deep/ .view-dialog>.el-dialog>.el-dialog__footer {
  padding-left: 0;
  padding-right: 0;
  text-align: center;
}

/deep/ .dialog-form>.el-form-item {
  margin-bottom: 30px;
}

/deep/ .dialog-form>.el-form-item>.el-form-item__content>.el-input>.el-input__inner {
  width: 220px;
  height: 34px;
  background: #FFFFFF;
  border: 1px solid #DCDEE2;
  border-radius: 3px;
}

/deep/ .dialog-form>.el-form-item>.el-form-item__content>.el-select>.el-input>.el-input__inner {
  width: 220px;
  height: 34px;
  background: #FFFFFF;
  border: 1px solid #DCDEE2;
  border-radius: 3px;
}

/deep/ .view-dialog>.el-dialog>.el-dialog__header>.el-dialog__headerbtn {
  top: 0;
}

/deep/ .view-dialog .el-form-item__content {
  width: 100%;
}
</style>
